package com.hellobike.haxing.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hellobike.haxing.common.vo.ProductResultCode;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.product.entity.Product;
import com.hellobike.haxing.modules.product.entity.Promotion;
import com.hellobike.haxing.modules.product.entity.PromotionFlash;
import com.hellobike.haxing.modules.product.entity.PromotionFlashSku;
import com.hellobike.haxing.modules.product.mapper.ProductMapper;
import com.hellobike.haxing.modules.product.mapper.PromotionFlashMapper;
import com.hellobike.haxing.modules.product.mapper.PromotionFlashSkuMapper;
import com.hellobike.haxing.modules.product.mapper.PromotionMapper;
import com.hellobike.haxing.modules.product.service.IPromotionFlashService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 限时秒杀
 * @Author: haxing-boot
 * @Date:   2020-01-31
 * @Version: V1.0
 */
@Service
public class PromotionFlashServiceImpl extends ServiceImpl<PromotionFlashMapper, PromotionFlash> implements IPromotionFlashService {

    @Autowired
    private PromotionFlashMapper promotionFlashMapper;
    @Autowired
    private PromotionFlashSkuMapper promotionFlashSkuMapper;
    @Autowired
    private PromotionMapper promotionMapper;
    @Autowired
    private ProductMapper productMapper;


    @Override
    public IPage<PromotionFlash> page(Page<PromotionFlash> page, QueryWrapper<PromotionFlash> queryWrapper) {
        IPage<PromotionFlash> pageList = promotionFlashMapper.selectPage(page, queryWrapper);
        fillProductInfo(pageList.getRecords());

        return pageList;
    }

    /**
     * 填充商品信息
     * @param promotionFlashList
     */
    private void fillProductInfo(List<PromotionFlash> promotionFlashList) {
        if (promotionFlashList != null && promotionFlashList.size() > 0) {
            List<Long> productIdList = promotionFlashList.stream().map(PromotionFlash::getProductId).distinct().collect(Collectors.toList());
            List<Product> productList = productMapper.selectBatchIds(productIdList);
            Map<Long, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getId, Function.identity()));
            promotionFlashList.forEach(promotionFlash -> {
                Product product = productMap.get(promotionFlash.getProductId());
                promotionFlash.setProductName(product.getTitle());
                promotionFlash.setSpuCode(product.getSpuCode());
            });
        }
    }

    //判断商品参加的活动时间是否重叠
    private boolean isProductPromotionTimeConflict(PromotionFlash promotionFlash) {
        List<Promotion> productPromotions = promotionMapper.getProductPromotions(promotionFlash.getProductId());
        if (productPromotions.size() > 0) {
            Promotion promotion = promotionMapper.selectById(promotionFlash.getPromotionId());
            for (Promotion otherPromotion : productPromotions) {
                if (otherPromotion.getId().equals(promotion.getId())) {
                    continue;
                }
                if (!(promotion.getBeginTime().after(otherPromotion.getEndTime()) || promotion.getEndTime().before(otherPromotion.getBeginTime()))) {
                    return true;
                }
            }
        }
        return false;
    }

    @Transactional
    @Override
    public Result savePromotionFlash(PromotionFlash promotionFlash) {
        //判断商品参加的活动时间是否重叠
        if (promotionFlash.getStatus() == 1 && isProductPromotionTimeConflict(promotionFlash)) {
            return Result.error("该商品已参与的其他活动与当前活动时间重叠，无法上架!");
        }

        //保存限时抢购商品
        promotionFlashMapper.insert(promotionFlash);
        //保存限时抢购sku列表
        if (promotionFlash.getFlashSkus() != null) {
            for (PromotionFlashSku flashSku : promotionFlash.getFlashSkus()) {
                flashSku.setFlashId(promotionFlash.getId());
                flashSku.setStockLeft(flashSku.getStockInit());
                promotionFlashSkuMapper.insert(flashSku);
            }
        }

        return Result.ok("添加成功!");
    }

    @Transactional
    @Override
    public Result updatePromotionFlash(PromotionFlash promotionFlash) {
        //判断商品参加的活动时间是否重叠
        if (promotionFlash.getStatus() == 1 && isProductPromotionTimeConflict(promotionFlash)) {
            return Result.error("该商品已参与的其他活动与当前活动时间重叠，无法上架!");
        }
        //更新限时抢购商品
        promotionFlashMapper.updateById(promotionFlash);
        //更新限时抢购sku列表
        if (promotionFlash.getFlashSkus() != null) {
            for (PromotionFlashSku flashSku : promotionFlash.getFlashSkus()) {
                if (flashSku.getId() == null) {
                    flashSku.setFlashId(promotionFlash.getId());
                    flashSku.setStockLeft(flashSku.getStockInit());
                    promotionFlashSkuMapper.insert(flashSku);
                } else {
                    Integer addStock;
                    PromotionFlashSku oldFlashSku = promotionFlashSkuMapper.selectById(flashSku.getId());
                    if ((addStock = flashSku.getStockInit() - oldFlashSku.getStockInit()) != 0) {
                        Integer stockLeft = oldFlashSku.getStockLeft() + addStock;
                        flashSku.setStockLeft(stockLeft < 0 ? 0 : stockLeft);
                    } else {
                        flashSku.setStockLeft(null);
                    }
                    promotionFlashSkuMapper.updateById(flashSku);
                }
            }
        }
        return Result.ok("编辑成功!");
    }

    @Override
    public Result changeStatus(Long id, Integer status) {
        if (status == 1) {
            PromotionFlash promotionFlash = promotionFlashMapper.selectById(id);
            if (promotionFlash != null && isProductPromotionTimeConflict(promotionFlash)) {
                return Result.error("该商品已参与的其他活动与当前活动时间重叠，无法上架!");
            }
        }
        PromotionFlash flashProduct = new PromotionFlash();
        flashProduct.setId(id);
        flashProduct.setStatus(status);
        promotionFlashMapper.updateById(flashProduct);
        return Result.ok("操作成功!");
    }

    @Override
    public PromotionFlash getPromotionFlashDetail(Long id) {
        PromotionFlash promotionFlash = promotionFlashMapper.selectById(id);
        if (promotionFlash != null) {
            List<PromotionFlashSku> flashSkus = promotionFlashSkuMapper.selectList(new QueryWrapper<PromotionFlashSku>().lambda().eq(PromotionFlashSku::getFlashId, id));
            promotionFlash.setFlashSkus(flashSkus);
        }
        return promotionFlash;
    }

    @Override
    public Result changeFlashSkuStock(Long flashSkuId, Integer changeNum) {
        int flag = promotionFlashSkuMapper.changeFlashSkuStock(flashSkuId, changeNum);
        if (flag == 0) {
            return Result.error(ProductResultCode.STOCK_NOT_ENOUGH, "库存不足");
        }
        return Result.ok();
    }
}
